--
-- Author: shunguo.chen
-- Date: 2017-11-27 11:42:45
--
-- MountController
--

local MountView = import("..views.MountView")
local MountSpeedView = import("..views.MountSpeedView")
local MountGetView = import("..views.MountGetView")
local MountSummonView = import("..views.MountSummonView")
local MountStarView = import("..views.MountStarView")
local MountQualityView = import("..views.MountQualityView")
local MountAttrView = import("..views.MountAttrView")
local MountNewView = import("..views.MountNewView")
require("app.ui.DelayCacheMgr")
local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)

end

function ClassRef:init()
	self._model = app:getInst("MountModel")

	-- 缓存新坐骑
	self._mountCache = nil
    -- 当前panel id
    self._curId = 0

	self._bagHandler = UD.bag:onChanged(handler(self, self.updateItem))
	self._mountHandler = UD:onChanged("mount",handler(self, self.updateMount))
	self._mountSoulHandler = UD:onChanged("mountSoul",handler(self, self.updateMountSoul))
	self._playerHandler = UD.player:onChanged(handler(self, self.updatePlayer))
	self._walletHandler = UD:onChanged("wallet", handler(self, self.updatePlayer))
    self._mountActiveHandler = UD:onChanged("activatedMount",handler(self, self.updateActiveMount))
    self._redPointHandler = UD.redPoint:onChanged(handler(self, self.updateRedPoint))
end

function ClassRef:removeListeners()
	self.super.removeListeners(self)

    UD.bag:unChanged(self._bagHandler)
	UD.redPoint:unChanged(self._redPointHandler)
	UD:unChanged("mount", self._mountHandler)
	UD:unChanged("mountSoul", self._mountSoulHandler)
	UD.player:unChanged(self._playerHandler)
	UD:unChanged("activatedMount", self._mountActiveHandler)
	UD:unChanged("wallet", self._walletHandler)
end


function ClassRef:openView(data)
	if cc.isDead(self._view) then
		self._view = MountView.new(app.mvc.VIEWTYPE_BLUR)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
		self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
	end
	self:addChild(self._view, data)
	self._view:show(data or 1)

    self._view:updateBtnRedPoint()
end

function ClassRef:clearView()
    self.super.clearView(self)

    self._curId = 0
    UD:clearMountsNew()
    UD.redPoint:clearStateByKey(Constant.FUNC_TYPE_MOUNT)
end

---------------------------------------------------------------
-- userdata 过来的更新
function ClassRef:updateMount(uid, mount, opt)
    -- release_print("==>mount updateMount", uid, opt, mount:getStar())

	self._model:updateMount(uid, mount, opt)
	if opt == "insert" then
		-- 抽奖获得的坐骑特殊处理
		if not app:sendMsg("MallController", "isInLottery") and 
			not app:sendMsg("MallController", "isInShopDraw") then
			DelayCacheMgr.registerDelayMsg(DelayCacheMgr.DelayConstant.GetMount,handler(self, self.openNewView), mount)
			--self:openNewView(mount)
		end
	end

	
	if not self:isViewAlive() then return end
	local panel = self._view:getPanel(self._curId)
	if opt == "update" then
		-- 更新坐骑，找到目标render，刷新一次即可
		local sv = panel:refreshScrollView()
		-- local renders = sv:getVisibleRenders()
		-- for i,render in ipairs(renders) do
		-- 	local data = render:getData()
		-- 	if data.uid == uid then
		-- 		release_print("==>mount updateMount refresh render")
		-- 		render:setData(mount)
		-- 		-- break
		-- 	else
		-- 		render:updateCanOperation()
		-- 	end
		-- end
	elseif opt == "insert" then
		-- 新获得的坐骑，立刻显示该坐骑
		self:onSwitchPanel(self._curId, uid)
	elseif opt == "reload" then
		self:onSwitchPanel(self._curId, uid)
	else
		-- 暂时没有删除坐骑的操作，不做处理

	end
end

function ClassRef:updatePlayer(name, old, new)
	if name == "mountUID" then
		self:onUpdateEquipMount()
	end
end

function ClassRef:updateRedPoint(changeKeys)
    if not self:isViewAlive() then return end

    if changeKeys[RedPointConstant.Mount_Ride] ~= nil or
        changeKeys[Constant.FUNC_TYPE_MOUNT_PIT] ~= nil then
        self._view:updateBtnRedPoint()
    end
end

-- 道具更新要刷新界面道具数量显示
function ClassRef:updateItem(uid,item,amountGot)
	if item.itemBagType ~= Enums.ItemBagType.item then return end
    if not item then return end
    if not self:isViewAlive() then return end

	-- MountStarView ui update
	local mount
	local view = self._view:getChildByName(MountStarView:getViewName())
	if view then
		mount = view:getMount()
		if mount:isRelatedItem(item.tid) then
			view:refreshStarCollect()
		end
	end

	-- MountQualityView ui update
	local view = self._view:getChildByName(MountQualityView:getViewName())
	if view then
		mount = view:getMount()
		if mount:isSoulItem(item.tid) then
			view:refreshMountCollect()
		end
	end

	local panel = self._view:getPanel(self._curId)
	mount = panel:getMount()

	-- 检查品质提升，更新收集ui
	if not mount:isMaxQuality() and mount:isSoulItem(item.tid) then
		panel:refreshMountCollect()
	end

	-- 检查星级提示，更新星级ui
	if self._curId == 2 then 
		if mount:haveMount() and not mount:isMaxStar() and mount:isRelatedItem(item.tid) then
			panel:refreshStarCollect()
		end
	end

	panel:refreshScrollView()
	if self._curId == 2 then
		panel:refreshActiveRenders()
	end
end

function ClassRef:updateMountSoul(id,mountSoul,amountGot,opt)
	if not mountSoul then return end
	if not self:isViewAlive() then return end

	-- MountQualityView ui update
	local mount
	local view = self._view:getChildByName(MountQualityView:getViewName())
	if view then
		mount = view:getMount()
		if mount:isSoulItem(mountSoul.id) then
			view:refreshMountCollect()
		end
	end

	if not self:isViewAlive() then return end
	local panel = self._view:getPanel(self._curId)
	mount = panel:getMount()

	-- 检查品质提升，更新收集ui
	if not mount:isMaxQuality() and mount:isSoulItem(mountSoul.id) then
		panel:refreshMountCollect()
	end
end

-- userdata 过来的更新
function ClassRef:updateActiveMount(uid, mount, opt)
	release_print("==>mount updateActiveMount", uid, opt, mount:getStar())

	if not self:isViewAlive() then return end
	if self._curId ~= 2 then return end

	local panel = self._view:getPanel(2)
	local activeRenders = panel:getActiveRenders()
	local render = activeRenders[mount.index]
	if opt == "delete" then
		render:setData()
	else
		render:setData(mount)
        if opt == "insert" then
            render:setSelected(true)
            panel:setCurActiveRender(render)
        end
	end
end

-- 坐骑装备／卸下成功
function ClassRef:onUpdateEquipMount()
	if not self:isViewAlive() then return end
	if self._curId ~= 1 then return end

	local panel = self._view:getPanel(1)
	panel:clearRiding()
	panel:refreshCurRender()
	panel:refreshMount()
end

-- 坐骑激活／卸下成功
function ClassRef:onUpdateActiveMount()
	if not self:isViewAlive() then return end
	if self._curId ~= 2 then return end

	local panel = self._view:getPanel(2)
	panel:refreshMount()
    panel:refreshRedPoint()
end

-- 升星成功
function ClassRef:onUpdateMountStar()
	if not self:isViewAlive() then return end
	if self._curId ~= 2 then return end

	local panel = self._view:getPanel(2)
	panel:refreshStar()
	panel:refreshScrollView()
	panel:refreshActiveRenders()
	release_print("==>mount onUpdateMountStar", panel:getMount():getStar())
end

-- 成功
function ClassRef:onUpdateMountQuality()
	if not self:isViewAlive() then return end
	if self._curId ~= 2 then return end

	local panel = self._view:getPanel(2)
	panel:refreshQuality()
end

------------------------------------------------------------
function ClassRef:onOperate(operate, param)
	-- print("MountController:onOperate operate = " .. operate)
	if operate == "openShare" then
		display.pushToast(L("tips_1110010"))
		-- app:sendMsg("ShareController", "shareMount")
	elseif operate == "openSpeed" then
		self:openSpeedView()
	elseif operate == "openCorePropStar" then
		self:openMountCorePropStarView()
	elseif operate == "openGet" then
		if param:canBeComposed() then
			local haveNum, needNum = param:getQualityCostNum()
			if haveNum < needNum then
				self:openGetView(param)
			else
				self:openSummonView(param)
			end
		else
			self:openGetView(param)
		end
	elseif operate == "openStar" then
		self:openStarView(param)
	elseif operate == "openQuality" then
        self:openQualityView(param)
	elseif operate == "openAttr" then
        self:openAttrView(param)
    elseif operate == "equipMount" then
        self._model:reqEquipMount(param.uid)
    elseif operate == "unequipMount" then
        self._model:reqUnEquipMount()
    elseif operate == "activeMount" then
    	if not UD:isActivatedMountFull() then
        	self._model:reqActivateMount(param.uid)
        else
        	display.pushToast(L("lua_code_text_382"))
        end
    elseif operate == "unactiveMount" then
        self._model:reqDeactivateMount(param.uid)
	end
end


function ClassRef:openSpeedView()
    local view = MountSpeedView.new()
    view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    local params = self._model:getSpeedData()
    view:refresh(params)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:openMountCorePropStarView()
	local MountCorePropStarView = require("app.mount.views.MountCorePropStarView")
	local view = MountCorePropStarView.new()
    view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:refresh(self._model:getMountsTotalStar())
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end


function ClassRef:openGetView(mount)
    local view = MountGetView.new()
	view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:onOperate(function(op, params)
        if op == "openFunc" then
			display.resourceGotoFeature(params)
        end
    end)
    view:refresh(mount)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:openSummonView(mount)
    local view = MountSummonView.new()
    view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:onOperate(function(op, params)
        if op == "summonMount" then
            self._model:reqComposeMount(mount.tid)
        end
    end)
    view:refresh(mount)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:openStarView(mount)
	if not self:isViewAlive() then return end

    local view = MountStarView.new()
    view:onCloseView(function(sender)
    	sender:removeFromParent()
    end)
    view:onOperate(function(op, params)
        if op == "starUp" then
            self._model:reqUpgradeMountStar(mount.uid)
        end
    end)
    view:refresh(mount)
    view:setName(view:getViewName())
    self._view:addChild(view)
    view:show()
end

function ClassRef:openQualityView(mount)
	if not self:isViewAlive() then return end

    local view = MountQualityView.new()
    view:onCloseView(function(sender)
    	sender:removeFromParent()
    end)
    view:onOperate(function(op, params)
        if op == "qualityUp" then
            self._model:reqUpgradeMountLevel(mount.uid)
        end
    end)
    view:refresh(mount)
    view:setName(view:getViewName())
    self._view:addChild(view)
    view:show()
end

function ClassRef:openAttrView(mount)
    local view = MountAttrView.new(app.mvc.VIEWTYPE_MODAL_BG)
    view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:refresh(self._model:getActiveData())
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

-- 剧情结束，显示获得新坐骑界面
function ClassRef:storyOver()
	if self._mountCache then
		self:openNewView(self._mountCache)
		self._mountCache = nil
	end
end

function ClassRef:openNewView(mount, tipStr)
	if BattleManager:isBattle() or StoryManager:isEnterStoryMode() then
		self._mountCache = mount
		DelayStack:pushToFront({name = "newMount"})
	else
		-- TODO csg 获得新坐骑，暂时只有一个
		UIHandler:getPopupUi():removeUIByKey(MountNewView:getViewName())

		-- 清空已经存在的引导
		app:sendMsg("GuideController", "closeView")

		local view = MountNewView.new()
		view:onCloseView(function(sender)
			-- 有可能是抽奖打开的，需要出发下个奖品展示
			app:sendMsg("MallController", "showNextLotteryResult")
			UIHandler:removePopupUiByKey(sender:getViewName())
		end)
		view:onOperate(function(op, params)
			if op == "shareMount" then
				-- TODO
				display.pushToast(L("lua_code_text_398"))
			end
		end)
		view:refresh(mount, tipStr)
		UIHandler:addPopupUi(view, view:getViewName())
		view:show()
	end
end

-- 1 MountPanel
-- 2 MountActivePanel
function ClassRef:onSwitchPanel(id, uid)
    if self._curId ~= id then
        if self._curId == 1 then
            UD.redPoint:clearStateByKey(RedPointConstant.Mount_Ride)
        elseif self._curId == 2 then
            UD.redPoint:clearStateByKey(Constant.FUNC_TYPE_MOUNT_PIT)
        end
    end

	self._curId = id
	if id == 1 then
		self:refreshPanel(uid)
	elseif id == 2 then
		self:refreshActivePanel(uid)
	end
end

-- 骑乘界面
function ClassRef:refreshPanel(showUid)
	local panel = self._view:getPanel(1)
	panel:clearSelect()

	local datas = self._model:getMountDatas(false, true)
	panel:reloadData(datas)
	-- local sv = panel:getScrollView()
	-- sv:showDataList(datas, nil, function(sender)
	-- 	panel:setCurRender(sender)
	-- end, function()
	-- 	-- 2. 默认坐骑：指定uid，在异步加载完成之后，选择特定的render
	-- 	if showUid then
	-- 		panel:selectRender(showUid)
	-- 	end
	-- end)
	-- sv:jumpToTop()
	-- 1. 默认坐骑：不指定uid，就第一个render
	if not showUid then
		-- local initRender = sv:getVisibleRender(1)
		-- initRender:setSelected(true)
		-- panel:setCurRender(initRender)
		panel:setSelectedByIndex(1)
	else
		panel:selectRender(showUid)
		-- 2. 默认坐骑：指定uid，先用数据刷新界面
		for i,mount in ipairs(datas) do
			if mount.uid == showUid then
				panel:refreshMount(mount)
				break
			end
		end
	end
	local totalNum, haveNum = self._model:getMountNumWithoutSpReward(datas)
	panel:setMountNum(haveNum, totalNum)
	panel:setTotalStar(self._model:getMountsTotalStar())
	panel:setMountSpeed(self._model:getSpeedData().curSpeed)
end

-- 兽栏界面
function ClassRef:refreshActivePanel(showUid)
	local panel = self._view:getPanel(2)
	panel:clearSelect()

	-- activeRenders
	local initActiveRender
	local activeRenders = panel:getActiveRenders()
	for i,render in ipairs(activeRenders) do
        local mount = UD:getActivatedMountByIndex(i)
        render:setData(mount)
        render:setSelected(false)
        render:setClickHandler(function(sender)
        	panel:setCurActiveRender(sender)
        	panel:setCurRenderData(sender:getData())
        end)
        if mount then
        	if showUid then
        		-- 1. 默认激活坐骑：指定uid，从激活坐骑中寻找指定uid的render
        		if showUid == mount.uid then
        			initActiveRender = render
	            	initActiveRender:setSelected(true)
        		end
        	else
        		-- 2.默认激活坐骑：未指定uid，从激活坐骑中寻找第一个render
	            if not initActiveRender then
	            	showUid = mount.uid
	            	initActiveRender = render
	            	initActiveRender:setSelected(true)
	           	end
	        end
        end
    end
    panel:setCurActiveRender(initActiveRender)

	local datas = self._model:getMountDatas(true, true)
	panel:reloadData(datas)
	
    -- sv
    -- local sv = panel:getScrollView()
	
	-- sv:showDataList(datas, nil, function(sender)
	-- 	panel:setCurRender(sender)
	-- 	local uid = sender:getData().uid
	-- 	panel:selectActiveRender(uid)
	-- end, function()
	-- 	-- 2. 默认坐骑：指定uid，在异步加载完成之后，选择特定的render
	-- 	if showUid then
	-- 		panel:selectRender(showUid)
	-- 	end
	-- end)
    -- sv:jumpToTop()

   	-- 1. 默认坐骑：不指定uid，就第一个render
	if not showUid then
		-- local initRender = sv:getVisibleRender(1)
		-- initRender:setSelected(true)
		-- panel:setCurRender(initRender)
		panel:setSelectedByIndex(1)
	else
		panel:selectRender(showUid)
		-- 2. 默认坐骑：指定uid，先用数据刷新界面
		for i,mount in ipairs(datas) do
			if mount.uid == showUid then
				panel:refreshMount(mount)
				break
			end
		end
	end
end

return ClassRef
